package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerState;

/**
 * @author: wxw
 * @ClassName: AuthFilter
 * @JdkVersion: JDK1.8
 * @Version: 1.0.0
 * @Since: 2025/2/6 10:16
 * @Description: token统一认证全局过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {



    /**
     * token认证的过滤逻辑
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求实例
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应实例
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String path = request.getURI().getPath();

        // 如果路径是登录，则放行到目标微服务
        if ("/user/api/v1/login/login_auth/".equals(path)) {
            return chain.filter(exchange);
        }
        // 如果不是登录，则获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        // 如果token为空，则返回错误信息401
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 如果token不为空，则验证token是否有效  解析token，如果不合法，响应401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claimsBody);
        if (result == 0) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 放行前从Token载荷里获取登录用户的Id
        String userId = claimsBody.get("id").toString();
        // 放行前 将获取到的用户ID设置到请求头
        request.mutate().header("userId",userId);

        // 合法 放行
     return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 数字越小，执行优先级越高
        return 0;
    }
}
